# -*- coding: utf-8 -*-
import logging as log
import uuid

import tornado

import cms_config
from app.base_controller import BaseController
from app.common import global_space
from app.models import VideoOrder, OrderTeam, OrderProducer, Producer, Team
from libs.util import check_param
from datetime import datetime
from django.db.models import Q

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)


# 项目经理订单信息汇总
class OrderSummary(BaseController):

    def get(self):
        session_id = self.get_argument("session_id", '')
        if check_param([session_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')
        manager_id = session.get('id')

        video_orders = VideoOrder.objects.filter(manager_id=manager_id).filter(order_status=VideoOrder.STATE_FINISH).all()
        total_order_count = len(video_orders)
        total_order_account = 0
        current_month_order_count = 0
        current_month_order_account = 0
        date_format_str = "%Y-%m"
        current_month = datetime.now().strftime(date_format_str)
        for o in video_orders:
            total_order_account += o.amount
            if o.end_time and o.end_time.strftime(date_format_str) == current_month:
                current_month_order_count += 1
                current_month_order_account += o.amount

        order_summary = {
            'total_order_count': total_order_count,
            'total_order_account': total_order_account * 0.01,
            'current_month_order_count': current_month_order_count,
            'current_month_order_account': current_month_order_account * 0.01,
        }

        return self.render_json(data=order_summary)


class OrderList(BaseController):

    def get_order_state_list(self, state):
        if state == 1:
            return [ VideoOrder.STATE_PENDING_ORDERS, VideoOrder.STATE_MATCHING_TEAM, VideoOrder.STATE_PENDING_START ]
        elif state == 2:
            return [ VideoOrder.STATE_WRITING, VideoOrder.STATE_SHOOTING, VideoOrder.STATE_CLIP, VideoOrder.STATE_PENDING_ACCEPTANCE, VideoOrder.STATE_PENDING_COMMENTS ]
        elif state == 3:
            return [ VideoOrder.STATE_REFUNDS, VideoOrder.STATE_FINISH ]
        elif state == 4:
            return [ VideoOrder.STATE_OBLIGATIONS ]
        elif state == 5:
            return [ VideoOrder.STATE_PENDING_ORDERS ]

    def get(self):
        session_id = self.get_argument("session_id", '')
        if check_param([session_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')
        manager_id = session.get('id')
        state = self.int_argument('state', 1)
        state_list = self.get_order_state_list(state)
        if state == 5:
            video_orders = VideoOrder.objects.filter(manager_id__isnull=True)
        elif state == 4:
            video_orders = VideoOrder.objects
        else:
            video_orders = VideoOrder.objects.filter(manager_id=manager_id)
        video_orders = video_orders.filter(order_status__in=state_list).order_by('state', '-create_time')
        
        paginator = self.pagination(video_orders.all(), page_num=int(self.get_argument("pageNum", 1)))
        return self.render_json(data=paginator)


class OrderDetail(BaseController):

    def get(self):
        session_id = self.get_argument("session_id", '')
        order_id = self.get_argument('order_id', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            
        
        return self.render_json(data=video_order.to_detail_dict())


class OrderCount(BaseController):

    def get(self):
        session_id = self.get_argument("session_id", '')
        state = self.int_argument('state', 5)
        if check_param([session_id, state]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_orders = VideoOrder.objects
        video_count = 0
        if state == 5:
            video_count = video_orders.filter(manager_id__isnull=True).filter(order_status=VideoOrder.STATE_PENDING_ORDERS).count()         
        
        return self.render_json(data={'count': video_count})


class OrderRequirementDetail(BaseController):

    def get(self):
        session_id = self.get_argument("session_id", '')
        order_id = self.get_argument('order_id', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            
        
        data = {
            'requirement': video_order.requirement,
            'user_remark': video_order.user_remark,
            'plan_suggest': video_order.plan_suggest,
        }
        if not data['user_remark']:
            data['user_remark'] = video_order.requirement
        return self.render_json(data=data)


class OrderPendingDetail(BaseController):

    def get(self):
        session_id = self.get_argument("session_id", '')
        order_id = self.get_argument('order_id', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).filter(order_status__in=[VideoOrder.STATE_PENDING_ORDERS, VideoOrder.STATE_MATCHING_TEAM, VideoOrder.STATE_PENDING_START]).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            
        
        rslt = video_order.contracting_info()
        return self.render_json(data=rslt)


class OrderProducerComments(BaseController):

    def get(self):
        session_id = self.get_argument("session_id", '')
        order_id = self.get_argument('order_id', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            
        data = [ op.to_comment_dict() for op in OrderProducer.objects.filter(order=video_order).all()]
        return self.render_json(data={'producers': data})


class OrderTeamComments(BaseController):

    def get(self):
        session_id = self.get_argument("session_id", '')
        order_id = self.get_argument('order_id', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            
        data = OrderTeam.objects.filter(order=video_order).first()
        return self.render_json(data={'team': data.to_comment_dict()})


class SubmitOrderProducerComment(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在') 

        comments_list = self.get_json_argument('comments', [])
        if not comments_list:
            return self.render_json(code=1001, msg='参数不全')
        for comment in comments_list:
            id = comment.get('id', '')
            remark = comment.get('remark', '')
            score = comment.get('score', 0)
            op = OrderProducer.objects.filter(id=id).first()
            if not op:
                return self.render_json(code=999, msg='数据不存在')
            op.remark = remark
            op.score = score
            op.order_status = OrderProducer.WC
            op.save()

        order_finish = True
        for op in OrderProducer.objects.filter(order=video_order).filter(state=0).all():
            if op.order_status != OrderProducer.WC:
                order_finish = False
                break
        if order_finish:
            video_order.order_status = VideoOrder.STATE_FINISH
            video_order.save()
        return self.render_json(msg="评价成功")


class SubmitTeamComment(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        id = self.get_json_argument('id', '')
        remark = self.get_json_argument('remark', '')
        score = self.get_json_argument('score', 0)
        if check_param([session_id, order_id, remark]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在') 
        vt = OrderTeam.objects.filter(id=id).first()
        if not vt:
            return self.render_json(code=999, msg='数据不存在')
        vt.remark = remark
        vt.score = score
        vt.order_status = OrderTeam.WC
        vt.save()

        video_order.order_status = VideoOrder.STATE_FINISH
        video_order.save()
        return self.render_json(msg="评价成功")


class ChangeDemand(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        user_remark = self.get_json_argument('user_remark', '')
        plan_suggest = self.get_json_argument('plan_suggest', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            
        video_order.user_remark = user_remark
        video_order.plan_suggest = plan_suggest
        video_order.save()
        return self.render_json(msg="保存成功")


class ModifyPrice(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        price = self.get_json_argument('price', 0)
        if check_param([session_id, order_id, price]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).filter(order_status=VideoOrder.STATE_OBLIGATIONS).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            

        video_order.amount = int(price) * 100
        video_order.save()
        return self.render_json(msg="改价成功")


class ModifyOrderProducer(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        id = self.get_json_argument('id', '')
        producer_id = self.get_json_argument('producer_id', 0)
        amount = self.get_json_argument('amount', 0)
        title = self.get_json_argument('title', '')
        if check_param([session_id, order_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        if not producer_id and not amount:
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')  

        if title and video_order.title != title:
            video_order.title = title
            video_order.save()          
        op = OrderProducer.objects.filter(order=video_order).filter(id=id).first()
        if not op:
            return self.render_json(code=999, msg='数据不存在')

        if not amount and (not op.start_time or not op.end_time):
            return self.render_json(code=999, msg='请设置工作时间') 

        msg = "派单成功"
        if producer_id:
            producer = Producer.objects.filter(id=producer_id).first()
            if not producer:
                return self.render_json(code=999, msg='接单人不存在')
            op.producer = producer
            op.order_status = OrderProducer.ZZZ
        if amount:
            amount = int(amount)
            msg = "保存成功"
            if amount > 0:
                op.amount = amount * 100
        op.save()

        # 所有人都配置好就开始进入编剧中
        start_plan = VideoOrder.objects.update_order_status(order_id)

        return self.render_json(msg=msg, data={'finish': start_plan})


class ModifyOrderTeam(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        id = self.get_json_argument('id', '')
        team_id = self.get_json_argument('team_id', 0)
        amount = self.get_json_argument('amount', 0)
        title = self.get_json_argument('title', '')
        if check_param([session_id, order_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        if not team_id and not amount:
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')   

        if title and video_order.title != title:
            video_order.title = title
            video_order.save()  

        ot = OrderTeam.objects.filter(order=video_order).filter(id=id).first()
        if not ot:
            return self.render_json(code=999, msg='数据不存在')

        if not amount:
            if not VideoOrder.objects.order_can_pending(order_id):
                return self.render_json(code=999, msg='请设置工作时间') 

        msg = "派单成功"
        team_ready = False
        if team_id:
            team = Team.objects.filter(id=team_id).first()
            if not team:
                return self.render_json(code=999, msg='接单人不存在')
            ot.team = team
            ot.order_status = OrderTeam.BJ
            team_ready = True
        if amount:
            msg = "修改成功"
            amount = int(amount)
            if amount > 0:
                ot.amount = amount * 100
        ot.save()

        # 设置好团队后订单进入编剧状态
        if team_ready:
            video_order.order_status = VideoOrder.STATE_WRITING
            video_order.save()

        return self.render_json(msg=msg)


class ModifyOrderStatus(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        state = self.get_json_argument('state', 0)
        if check_param([session_id, order_id, state]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在')            
        
        video_order.order_status = state
        video_order.save()

        return self.render_json(msg='保存成功')


class ModifyPendingInfo(BaseController):

    def invalidate_datetime(self, start_time, end_time):
        if not start_time or not end_time:
            return False
        if start_time.replace(tzinfo=None) > end_time.replace(tzinfo=None):
            return True
        return False

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        id = self.get_json_argument('id', 0)
        key = self.get_json_argument('key', '')
        value = self.get_json_argument('value', '')
        title = self.get_json_argument('title', '')
        if check_param([session_id, order_id, id, key, value]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).filter(~Q(order_status__in=[VideoOrder.STATE_FINISH, VideoOrder.STATE_CACEL, VideoOrder.STATE_OBLIGATIONS])).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在') 

        if title and video_order.title != title:
            video_order.title = title
            video_order.save()

        if key == 'rate':
            value = value * 0.01

        if video_order.producer_type == VideoOrder.OVERALL_CONTRACTING:
            update_data = {key: value}
            if key == 'start_time':
                update_data['plan_start_time'] = value
            elif key == 'end_time':
                update_data['edit_end_time'] = value
            OrderTeam.objects.filter(id=id).update(**update_data)
            if key in ['start_time', 'end_time']:
                VideoOrder.objects.filter(order_id=order_id).update(**{key: value})
            query_result = OrderTeam.objects.filter(id=id).first()
        else:
            query_result = OrderProducer.objects.filter(id=id).first()
            if not query_result:
                return self.render_json(code=999, msg='修改的数据不存在') 
            if key == 'start_time':
                tmp_start_time = datetime.strptime(value, '%Y-%m-%d')
                if self.invalidate_datetime(tmp_start_time, query_result.end_time):
                    return self.render_json(code=999, msg='开始时间不能超过结束时间')   
                if query_result.end_time:
                    query_result.excute_day = (query_result.end_time.replace(tzinfo=None) - tmp_start_time.replace(tzinfo=None)).days + 1
                query_result.start_time = tmp_start_time    
            elif key == 'end_time':
                tmp_end_time = datetime.strptime(value, '%Y-%m-%d')
                if self.invalidate_datetime(query_result.start_time, tmp_end_time):
                    return self.render_json(code=999, msg='结束时间不能小于结束时间')
                if query_result.start_time:
                    query_result.excute_day = (tmp_end_time.replace(tzinfo=None) - query_result.start_time.replace(tzinfo=None)).days + 1
                query_result.end_time = tmp_end_time
            query_result.save()


        # 更新订单开始，结束时间
        VideoOrder.objects.update_start_and_end_time(order_id)

        return self.render_json(msg="保存成功", data=query_result.to_pending_dict())


class ModifyOrderCommission(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        id = self.get_json_argument('id', 0)
        rate = self.get_json_argument('rate', '')
        title = self.get_json_argument('title', '')
        if check_param([session_id, order_id, id, rate]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).filter(~Q(order_status__in=[VideoOrder.STATE_FINISH, VideoOrder.STATE_CACEL, VideoOrder.STATE_OBLIGATIONS])).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在') 

        if title and video_order.title != title:
            video_order.title = title
            video_order.save()

        query_result = OrderTeam.objects.filter(id=id).first()
        if not query_result:
            return self.render_json(code=999, msg='修改的数据不存在') 
        
        rate = rate * 0.01
        amount = query_result.price * rate
        query_result.rate = rate
        query_result.amount = amount
        query_result.save()

        return self.render_json(data={'rate': query_result.rate, 'amount': query_result.amount }, msg="保存成功")



class ModifyProducerType(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        producer_type = self.get_json_argument('producer_type', 0)
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).filter(order_status__in=[VideoOrder.STATE_PENDING_ORDERS, VideoOrder.STATE_MATCHING_TEAM, VideoOrder.STATE_PENDING_START]).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在') 

        video_order.producer_type = producer_type
        video_order.save()
        OrderTeam.objects.filter(order=video_order).all().update(state=(0 if producer_type == VideoOrder.OVERALL_CONTRACTING else 1))
        OrderProducer.objects.filter(order=video_order).all().update(state=(1 if producer_type == VideoOrder.OVERALL_CONTRACTING else 0))

        video_order = VideoOrder.objects.filter(order_id=order_id).first()

        return self.render_json(data=video_order.contracting_info())


class PickupOrder(BaseController):

    def post(self):
        """项目经理领取订单
        """
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).filter(order_status=VideoOrder.STATE_PENDING_ORDERS).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在') 
        if video_order.manager_id:
            return self.render_json(code=999, msg='领取失败！订单已被其他项目经理领取') 

        video_order.manager_id = session.get('id')
        video_order.save()

        return self.render_json(msg='订单领取成功，请前往准备中列表查看')


class ModifyAutoSendOrder(BaseController):

    def post(self):
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_id', '')
        title = self.get_json_argument('title', '')
        if check_param([session_id, order_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).filter(order_status__in=[VideoOrder.STATE_PENDING_ORDERS, VideoOrder.STATE_MATCHING_TEAM, VideoOrder.STATE_PENDING_START]).first()
        if not video_order:
            return self.render_json(code=999, msg='订单不存在') 

        if not title and not video_order.title:
            return self.render_json(code=999, msg='请填写影片名称')  

        if title and video_order.title != title:
            video_order.title = title
            video_order.save()           

        if not VideoOrder.objects.order_can_pending(order_id):
            return self.render_json(code=999, msg='请设置工作时间') 

        video_order.order_status =  VideoOrder.STATE_MATCHING_TEAM
        video_order.save()
        if video_order.producer_type == VideoOrder.OVERALL_CONTRACTING:
            OrderTeam.objects.filter(order=video_order).all().update(**{'order_status': OrderTeam.PP, 'state': 0})
            OrderProducer.objects.filter(order=video_order).all().update(state=1)
        else:
            OrderTeam.objects.filter(order=video_order).all().update(state=1)
            OrderProducer.objects.filter(order=video_order).all().update(**{'order_status': OrderProducer.PP, 'state': 0})

        return self.render_json(msg='修改成功')



